package com.freeman.cement.controller;

import com.alibaba.fastjson.JSONObject;
import com.freeman.cement.entity.ResponseResult;
import com.freeman.cement.entity.Staff;
import com.freeman.cement.entity.User;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.service.StaffService;
import com.freeman.cement.system.BllFrame;
import com.freeman.cement.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import org.slf4j.Logger;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 66
 */
@RestController
@CrossOrigin    //允许跨域访问
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private StaffService service;

    /*
     * @RequestParam("name")
     * 该注解表明"name"参数必须存在
     *
     * */
    //登录方法
    //访问地址：http://localhost:8080/sysmanage/login?username=001&password=123456

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestParam("username") String username, @RequestParam("password") String password) {
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            Staff staff = service.UserLoginCheck(username, password);
            if (staff != null) {
                if (staff.getStatus().equals("停用")) {
                    throw new AppException(AppExceptionCodeMsg.USERNAME_IS_INVALID);
                } else {
                    //登录成功，生成token
                    String token = JwtUtil.generateToken(Integer.toString(staff.getId()), staff.getRole(), staff.getUsername());
                    //每次登录时更新缓存中的登录人员信息
                    if (BllFrame.loginUsrsCache.containsKey(staff.getUsername())) {
                        logger.info("更新已存在的用户缓存，username: {}, 当前缓存内容: {}", 
                            staff.getUsername(), 
                            BllFrame.loginUsrsCache.entrySet().stream()
                                .map(e -> String.format("[%s: %s]", e.getKey(), e.getValue().getUsername()))
                                .collect(Collectors.joining(", ")));
                        BllFrame.loginUsrsCache.remove(staff.getUsername());
                    }
                    User usr = new User();
                    usr.setToken(token);
                    usr.setId(staff.getId());
                    usr.setUserCode(staff.getUserCode());
                    usr.setUsername(staff.getUsername());
                    usr.setRealname(staff.getRealname());
                    usr.setGroupId(staff.getGroupId());
                    usr.setDeptName(staff.getDeptName());
                    usr.setDeptId(staff.getDeptId());
                    usr.setRole(staff.getRole());
                    usr.setWorksection(staff.getWorksection());
                    usr.setLastActiveTime(new Date());
                    BllFrame.loginUsrsCache.put(usr.getUsername(), usr);
                    logger.info("添加新用户到缓存，username: {}, 当前缓存内容: {}", 
                        usr.getUsername(),
                        BllFrame.loginUsrsCache.entrySet().stream()
                            .map(e -> String.format("[%s: %s]", e.getKey(), e.getValue().getUsername()))
                            .collect(Collectors.joining(", ")));
                    //返回数据
                    logger.info("Login--->" + "用户名:" + username + "登录成功");
                    return ResponseResult.success("登录成功", usr);
                }
            } else {
                System.out.println("用户名:" + username + "登录验证失败");
                logger.info("Login--->" + "用户名:" + username + "登录验证失败");
                throw new AppException(AppExceptionCodeMsg.USERNAME_OR_PASSWORD_WRONG);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

    /**
     * 登出
     * 访问logout，必须带有token
     * 应当要求前端在收到回应后，删除本地的token
     *
     * @param id
     * @return
     */
    @PostMapping("/logout")
    public ResponseResult logout(@RequestParam("id") int id) {
        //这里能接收到id，说明token是对的，也就是用户登录成功过
        if (id > 0) {
            service.UserLogout(id);
            // 清理缓存
            BllFrame.loginUsrsCache.entrySet().removeIf(entry -> entry.getValue().getId().equals(id));
            logger.info("Logout--->" + "用户ID:" + id + "登出成功");
            return ResponseResult.success("退出成功", null);
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }


}
